package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "DutyStaffServlet", value = "/DutyStaffServlet")
public class DutyStaffServlet extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        if ("list".equals(action)) {
            listStaff(out);
        } else if ("get".equals(action)) {
            getStaff(request, out);
        } else if ("delete".equals(action)) {
            deleteStaff(request, out);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        if ("add".equals(action)) {
            addStaff(request, out);
        } else if ("update".equals(action)) {
            updateStaff(request, out);
        }
    }

    // 加载值班人员列表
    private void listStaff(PrintWriter out) {
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM duty_staff ORDER BY duty_time")) {

            StringBuilder html = new StringBuilder();
            html.append("<table class='staff-table'>")
                    .append("<thead>")
                    .append("<tr>")
                    .append("<th>ID</th>")
                    .append("<th>姓名</th>")
                    .append("<th>性别</th>")
                    .append("<th>值班时间</th>")
                    .append("<th>操作</th>")
                    .append("</tr>")
                    .append("</thead>")
                    .append("<tbody>");

            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                Timestamp dutyTime = rs.getTimestamp("duty_time");

                html.append("<tr>")
                        .append("<td>").append(id).append("</td>")
                        .append("<td>").append(name).append("</td>")
                        .append("<td>").append(gender).append("</td>")
                        .append("<td>").append(formatDateTime(dutyTime)).append("</td>")
                        .append("<td>")
                        .append("<button class='operation-btn edit-btn' onclick=\"showEditModal(").append(id).append(")\">编辑</button>")
                        .append("<button class='operation-btn delete-btn' onclick=\"deleteStaff(").append(id).append(")\">删除</button>")
                        .append("</td>")
                        .append("</tr>");
            }
            html.append("</tbody></table>");
            out.println(html.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("error: 获取数据失败 - " + e.getMessage());
        }
    }

    // 获取单个值班人员信息
    private void getStaff(HttpServletRequest request, PrintWriter out) {
        int id = Integer.parseInt(request.getParameter("id"));
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM duty_staff WHERE id = ?")) {

            pstmt.setInt(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    out.println("{");
                    out.println("\"id\":" + rs.getInt("id") + ",");
                    out.println("\"name\":\"" + rs.getString("name") + "\",");
                    out.println("\"gender\":\"" + rs.getString("gender") + "\",");
                    out.println("\"dutyTime\":\"" + formatDateTime(rs.getTimestamp("duty_time")) + "\"");
                    out.println("}");
                } else {
                    out.println("error: 未找到该值班人员");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("error: 获取数据失败 - " + e.getMessage());
        }
    }

    // 删除值班人员
    private void deleteStaff(HttpServletRequest request, PrintWriter out) {
        int id = Integer.parseInt(request.getParameter("id"));
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement("DELETE FROM duty_staff WHERE id = ?")) {

            pstmt.setInt(1, id);
            int rows = pstmt.executeUpdate();
            if (rows > 0) {
                out.println("success");
            } else {
                out.println("error: 删除失败，未找到该记录");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("error: 删除失败 - " + e.getMessage());
        }
    }

    // 添加值班人员
    private void addStaff(HttpServletRequest request, PrintWriter out) {
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String dutyTimeStr = request.getParameter("dutyTime");

        try {
            String formattedTime = dutyTimeStr.replace("T", " ");
            if (formattedTime.length() == 16) {
                formattedTime += ":00";
            }
            Timestamp dutyTime = Timestamp.valueOf(formattedTime);

            try (Connection conn = getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(
                         "INSERT INTO duty_staff (name, gender, duty_time) VALUES (?, ?, ?)")) {

                pstmt.setString(1, name);
                pstmt.setString(2, gender);
                pstmt.setTimestamp(3, dutyTime);
                pstmt.executeUpdate();
                out.println("success");
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            out.println("error: 日期格式错误，请输入正确的时间格式（如：2024-10-01T12:00）");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("error: 添加失败 - " + e.getMessage());
        }
    }

    // 更新值班人员
    private void updateStaff(HttpServletRequest request, PrintWriter out) {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String dutyTimeStr = request.getParameter("dutyTime");

        try {
            String formattedTime = dutyTimeStr.replace("T", " ");
            if (formattedTime.length() == 16) {
                formattedTime += ":00";
            }
            Timestamp dutyTime = Timestamp.valueOf(formattedTime);

            try (Connection conn = getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(
                         "UPDATE duty_staff SET name = ?, gender = ?, duty_time = ? WHERE id = ?")) {

                pstmt.setString(1, name);
                pstmt.setString(2, gender);
                pstmt.setTimestamp(3, dutyTime);
                pstmt.setInt(4, id);
                int rows = pstmt.executeUpdate();

                if (rows > 0) {
                    out.println("success");
                } else {
                    out.println("error: 更新失败，未找到该记录");
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            out.println("error: 日期格式错误，请输入正确的时间格式（如：2024-10-01T12:00）");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("error: 更新失败 - " + e.getMessage());
        }
    }

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    // 格式化时间
    private String formatDateTime(Timestamp timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(timestamp);
    }
}